package com.xinsoft.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.CusTestPointDataDTO;
import com.xinsoft.entity.dto.CusWarnDataPageParam;
import com.xinsoft.entity.po.CusDevice;
import com.xinsoft.entity.po.CusTestPoint;
import com.xinsoft.entity.po.CusWarnData;
import com.xinsoft.entity.po.CusWarnRule;
import com.xinsoft.service.*;
import com.xinsoft.mapper.CusWarnDataMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @author hsm
* @description 针对表【cus_warn_data(告警数据)】的数据库操作Service实现
* @createDate 2023-07-13 15:00:44
*/
@Service
public class CusWarnDataServiceImpl extends ServiceImpl<CusWarnDataMapper, CusWarnData>
    implements CusWarnDataService{

    @Resource
    public CusDeviceService cusDeviceService;
    @Resource
    public CusWarnRuleService cusWarnRuleService;

    @Resource
    public SysNoticeService sysNoticeService;

    @Resource
    public CusTestPointService cusTestPointService;

    /**
     * 判断测点数据是否需要告警
     * @param dataDTOList
     */
    @Override
    public void sendTestPointWarn(List<CusTestPointDataDTO> dataDTOList) {
        if(CollectionUtil.isEmpty(dataDTOList)){
            return;
        }
        List<CusWarnData> dataList = CollectionUtil.newArrayList();

        for (CusTestPointDataDTO cusTestPointDataDTO : dataDTOList) {
            CusTestPoint testPoint =  cusTestPointService.getById(cusTestPointDataDTO.getTestPointId());
            CusWarnRule cusWarnRule =cusWarnRuleService.getById(testPoint.getWarnRuleId());
            CusDevice cusDevice = cusDeviceService.getById(testPoint.getDeviceId());
            if(cusWarnRule==null || testPoint==null || cusDevice==null){
                continue;
            }

            CusWarnData cusWarnData = new CusWarnData();
            dataList.add(cusWarnData);
            cusWarnData.setDeviceId(testPoint.getDeviceId());
            cusWarnData.setDeviceName(cusDevice.getDeviceName());
            cusWarnData.setTestPointId(testPoint.getId());
            cusWarnData.setTestPointName(testPoint.getTestPointName());
            cusWarnData.setWarnRuleId(cusWarnRule.getId());
            cusWarnData.setRuleName(cusWarnRule.getRuleName());
            cusWarnData.setTestPointValue(cusTestPointDataDTO.getTestPointValue());
            cusWarnData.setRuleValue(cusWarnRule.getRuleValue());
            cusWarnData.setRuleMin(cusWarnRule.getRuleMin());
            cusWarnData.setRuleMax(cusWarnRule.getRuleMax());
            cusWarnData.setDoRead(0);
            String noticeContext="";
            // 上下限
            if(cusWarnRule.getRuleMax()!=null && cusWarnRule.getRuleMin()!=null){
                if(cusWarnRule.getRuleMax().compareTo(new BigDecimal(cusTestPointDataDTO.getTestPointValue()))<0||
                        cusWarnRule.getRuleMin().compareTo(new BigDecimal(cusTestPointDataDTO.getTestPointValue()))>0) {
                    List<String> paramValues = new ArrayList<>();
                    Integer actionId  = Const.ACTION.DEVICE_WARN;
                    sysNoticeService.sendNoticeByActionId(paramValues,actionId);
                    noticeContext = "设备："+cusDevice.getDeviceName()+",测点："+testPoint.getTestPointName()+",值["+cusTestPointDataDTO.getTestPointValue()+"]"+"已超出范围值"+
                            "["+cusWarnRule.getRuleMin()+"-"+cusWarnRule.getRuleMax()+"].";

                }
            }

            // 标准值
            if(StrUtil.isNotEmpty(cusWarnRule.getRuleValue())){
                if(!StringUtils.equals(cusWarnRule.getRuleValue(),cusTestPointDataDTO.getTestPointId().toString())){
                    List<String> paramValues = new ArrayList<>();
                    Integer actionId  = Const.ACTION.DEVICE_WARN;
                    sysNoticeService.sendNoticeByActionId(paramValues,actionId);
                    noticeContext = "设备："+cusDevice.getDeviceName()+",测点："+testPoint.getTestPointName()+",值["+cusTestPointDataDTO.getTestPointValue()+"]"+"异常，标准值为："+
                            "["+cusWarnRule.getRuleValue()+"].";
                }
            }
            cusWarnData.setNoticeContext(noticeContext);
            dataList.add(cusWarnData);
        }
        if(CollectionUtil.isNotEmpty(dataList)){
            this.saveBatch(dataList);
        }
    }

    /**
     * 分页
     * @param param
     * @return
     */
    @Override
    public IPage<CusWarnData> findPageListByParam(CusWarnDataPageParam param) {
        //分页
        Page<CusWarnData> page = new Page<CusWarnData>(param.getCurrentPage(), param.getPageSize());
        QueryWrapper<CusWarnData> queryWrapper = new QueryWrapper<>();
        //查询条件
        queryWrapper.like(StrUtil.isNotEmpty(param.getDeviceName()), "device_name", param.getDeviceName());
        queryWrapper.like(StrUtil.isNotEmpty(param.getTestPointName()), "test_point_name", param.getTestPointName());
        queryWrapper.eq(param.getDoRead()!=null, "do_read", param.getDoRead());
        IPage<CusWarnData> resultPage = this.baseMapper.selectPage(page, queryWrapper);
        return resultPage;
    }

    /**
     * 删除
     * @param ids
     */
    @Override
    public void del(List<Integer> ids) {
        QueryWrapper<CusWarnData> query = new QueryWrapper<>();
        //启用
        query.eq("do_read", 0);
        query.in("id", ids);
        List<CusWarnData> rules = this.list(query);
        //判断是否已启用
        if (CollectionUtil.isNotEmpty(rules)) {
            throw new BDException("操作失败，" + rules.get(0).getRuleName() + "未读无法删除！");
        }
        // 删除
        removeByIds(ids);

    }

    @Override
    public void read(List<Integer> ids) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        //已读
        updateWrapper.set("do_read",1);
        updateWrapper.in("id", ids);
        update(updateWrapper);
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @Override
    public CusWarnData getCusWarnData(Integer id) {

        return getById(id);
    }

}




